import { StyleProvider } from "@ant-design/cssinjs"
import { Skeleton } from "antd"
import OICardStyle from "data-text:~maincontent/MainContent.module.css"
import tailwindCss from "data-text:~style.css"
import antdResetCss from "data-text:antd/dist/reset.css"
import highlightcss from "data-text:highlight.js/styles/atom-one-dark-reasonable.css"
import type { PlasmoCSConfig, PlasmoGetShadowHostId } from "plasmo"
import React, { lazy, Suspense, useEffect, useState, type FC } from "react"
import { createRoot } from "react-dom/client"

import { sendToBackground, type PlasmoMessaging } from "@plasmohq/messaging"
import { useMessage, usePort } from "@plasmohq/messaging/hook"

import MainContent from "~maincontent/MainContent"
import { useChatStore } from "~store/chatStore"
import { useTokenStroe } from "~store/tokenStore"
import { useUIcontentStore } from "~store/uicontentStore"
import { ThemeProvider } from "~theme"
import type { TokenStateObj } from "~type/tokenType"
import type { UIContentState } from "~type/UIcontent"
import { getStyleContainerRoot } from "~util"

export const config: PlasmoCSConfig = {
  matches: ["<all_urls>"]

  // all_frames: true
}
export const HOST_ID = process.env.PLASMO_PUBLIC_CONTENT_HOST_ID

export const getShadowHostId: PlasmoGetShadowHostId = () => HOST_ID
export const getStyle = () => {
  const cssArray = [antdResetCss, OICardStyle, highlightcss, tailwindCss]
  const style = document.createElement("style")
  style.textContent = cssArray.join("\n")
  return style
}

export default function PlasmoOverlay() {
  const showUI = useUIcontentStore((state) => state.showUI)
  const setShowUI = useUIcontentStore((state) => state.setShowUI)
  const setReqToken = useTokenStroe((state) => state.setReqToken)
  const dellAllToken = useTokenStroe((state) => state.dellAllToken)
  const setToken = useTokenStroe((state) => state.setToken)
  const delContent = useChatStore((state) => state.delContent)

  const handle: PlasmoMessaging.Handler<
    "AiEnable",
    UIContentState,
    any
  > = async (req, res) => {
    if (req.name === "AiEnable") {
      if (showUI != req.body.showUI) setShowUI(req.body.showUI)
      res.send({ message: "success", status: 200 })
    }
  }
  useMessage<UIContentState, any>(handle)
  const tokenPort = usePort<any, TokenStateObj>("token")
  const onkeydown = (e: KeyboardEvent) => {
    // console.log("onkeydown", e)
    e.stopPropagation()
    if (e.keyCode === 27 || e.key === "Escape") {
      setShowUI(false)
    } else if (e.metaKey && e.altKey && (e.key === "a" || e.keyCode == 65)) {
      setShowUI(!showUI)
    }
  }
  useEffect(() => {
    const elestyle = document.createElement("style")
    elestyle.textContent = `
    :root{
      --myoi-font-size:16px !important;
    }
    html{
      font-size:var(--myoi-font-size)
    }
   `
    document.head.appendChild(elestyle)
    // delContent()
    // dellAtllToken()hy123456

    tokenPort.send({})
  }, [])
  useEffect(() => {
    document.addEventListener("keydown", onkeydown)
    return () => {
      // console.log("remove")
      document.removeEventListener("keydown", onkeydown)
    }
  })
  useEffect(() => {
    sendToBackground({
      name: "uiContent",
      body: {
        showUI: showUI
      }
    })
  }, [showUI])
  useEffect(() => {
    if (tokenPort.data != undefined) {
      setReqToken(tokenPort.data.reqToken)
      setToken(tokenPort.data.token)
    }
  }, [tokenPort.data])
  return (
    <>
      {showUI ? (
        <ThemeProvider>
          <StyleProvider
            container={document.getElementById(HOST_ID).shadowRoot}>
            <MainContent></MainContent>
          </StyleProvider>
        </ThemeProvider>
      ) : (
        <></>
      )}
    </>
  )
}
